package com.jdew.thkj.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jdew.thkj.R;
import com.jdew.thkj.adapter.ProductAdapter;
import com.jdew.thkj.adapter.WrapAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.TokenBean;
import com.jdew.thkj.bean.ZhaoshangBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/8/7.
 */

public class TaoBaoActivity extends BaseActivity {
    @Bind(R.id.recycleView)
    RecyclerView recycleView;
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    private ImageView search;
    private ProductAdapter adapter;
    private WrapAdapter<ProductAdapter> madapter;
    private List<ZhaoshangBean.DataBean.TbkUatmFavoritesItemGetResponseBean.ResultsBean.UatmTbkItemBean> list = new ArrayList<>();
    private int page = 1;
    private boolean isLoading;
    private String itemid;
    private int totalSize;

    @Override
    public int bindLayout() {
        return R.layout.activity_taobao;
    }

    @Override
    public void initView(View view) {
        title.setText("淘宝");
        back.setVisibility(View.VISIBLE);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        back.setOnClickListener(this);
        adapter = new ProductAdapter(this, list);
        madapter = new WrapAdapter(adapter);
        madapter.adjustSpanSize(recycleView);
        addHeaderView();
        RequestData();
        initRefresh();
        setRecycleView();
        setRcycleview(recycleView, madapter);
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(TaoBaoActivity.this, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    itemid = list.get(position).getNum_iid();
                    toDetail();
                }
            }
        });
        changeStatusBarTextColor();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.search: {
                startActivity(MainSearchActivity.class);
            }
            break;
            default:
                break;
        }
    }

    private void addHeaderView() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.head_taobao, null);
        search = layout.findViewById(R.id.search);
        search.setOnClickListener(this);
        madapter.addHeaderView(layout);
    }

    public void RequestData() {

        String timesamp=RegexValidateUtils.getTime13();
        String numsamp=RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetHomeList(page, RegexValidateUtils.getUniquePsuedoID(),timesamp,numsamp,MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp+numsamp+RegexValidateUtils.getUniquePsuedoID()+sp.getString("SignToken","")+"PageIndex"+page)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<ZhaoshangBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(ZhaoshangBean bean) {
                if (bean.isSuccess()) {
                    if (null == bean.getData()) {
                        isLoading = false;
                        swipeRefreshLayout.setRefreshing(false);
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    totalSize = Integer.parseInt(bean.getData().getTbk_uatm_favorites_item_get_response().getTotal_results());
                    if (page == 1) {
                        list.clear();
                        adapter.setDataList(list);
                    }
                    list.addAll(bean.getData().getTbk_uatm_favorites_item_get_response().getResults().getUatm_tbk_item());
                    adapter.setDataList(list);
                    if (list.size() == totalSize) {
                        isLoading = true;
                        adapter.changeMoreStatus(adapter.NO_LOAD_MORE);
                        madapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    adapter.changeMoreStatus(adapter.LOADING_MORE);
                    isLoading = false;
                    madapter.notifyItemRemoved(adapter.getItemCount());
                }
            }
        });
    }

    private void initRefresh() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                RequestData();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    public void toDetail() {
        Bundle b = new Bundle();
        b.putSerializable("itemId", itemid);
        startActivity(TbProductDetailActivity.class, b);
    }

    public void setRecycleView() {
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                LinearLayoutManager linearManager = null;
                if (layoutManager instanceof LinearLayoutManager) {
                    linearManager = (LinearLayoutManager) layoutManager;
                }
                int lastVisibleItemPosition = linearManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == madapter.getItemCount()) {
                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        madapter.notifyItemRemoved(madapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        page++;
                        RequestData();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void changeStatusBarTextColor() {
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = this.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.color_ffffff));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//设置状态栏黑色字体
        }
    }
}
